<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h2>数据概览</h2>
      <p class="subtitle">系统核心数据统计</p>
    </div>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-card stat-card-primary">
            <div class="stat-icon">
              <el-icon :size="32"><User /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalUsers }}</div>
              <div class="stat-label">总用户数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-success">
            <div class="stat-icon">
              <el-icon :size="32"><Reading /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalWords }}</div>
              <div class="stat-label">单词总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-warning">
            <div class="stat-icon">
              <el-icon :size="32"><Collection /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalWordbooks }}</div>
              <div class="stat-label">词书总数</div>
            </div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-card stat-card-danger">
            <div class="stat-icon">
              <el-icon :size="32"><Histogram /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalStudyRecords }}</div>
              <div class="stat-label">学习记录</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="charts-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-card">
            <h3>用户增长趋势</h3>
            <div ref="userGrowthChartRef" class="chart-container"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-card">
            <h3>学习活跃度</h3>
            <div ref="studyActivityChartRef" class="chart-container"></div>
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import {
  User,
  Reading,
  Collection,
  Histogram
} from '@element-plus/icons-vue'
import { getStatistics, getUserGrowthTrend, getStudyActivityTrend } from '../api/statistics'

// 统计数据
const statistics = ref({
  totalUsers: 0,
  totalWords: 0,
  totalWordbooks: 0,
  totalStudyRecords: 0
})

// 图表引用
const userGrowthChartRef = ref(null)
const studyActivityChartRef = ref(null)
let userGrowthChart = null
let studyActivityChart = null

onMounted(() => {
  loadStatistics()
  initCharts()
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => {
  // 销毁图表实例
  if (userGrowthChart) {
    userGrowthChart.dispose()
  }
  if (studyActivityChart) {
    studyActivityChart.dispose()
  }
  window.removeEventListener('resize', handleResize)
})

// 加载统计数据
const loadStatistics = async () => {
  try {
    const response = await getStatistics()
    if (response.code === 200) {
      statistics.value = response.data
    } else {
      ElMessage.error(response.message || '加载统计数据失败')
    }
  } catch (error) {
    console.error('加载统计数据失败：', error)
    ElMessage.error('加载统计数据失败')
  }
}

// 初始化图表
const initCharts = () => {
  initUserGrowthChart()
  initStudyActivityChart()
}

// 初始化用户增长趋势图表
const initUserGrowthChart = async () => {
  if (!userGrowthChartRef.value) return
  
  userGrowthChart = echarts.init(userGrowthChartRef.value)
  
  try {
    const response = await getUserGrowthTrend(30)
    if (response.code === 200) {
      const chartData = response.data
      const dates = chartData.map(item => {
        const date = new Date(item.date)
        return `${date.getMonth() + 1}/${date.getDate()}`
      })
      const userCounts = chartData.map(item => item.count)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            interval: 4
          }
        },
        yAxis: {
          type: 'value',
          name: '用户数'
        },
        series: [
          {
            name: '用户数',
            type: 'line',
            smooth: true,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: 'rgba(102, 126, 234, 0.5)' },
                { offset: 1, color: 'rgba(102, 126, 234, 0.1)' }
              ])
            },
            lineStyle: {
              color: '#667eea',
              width: 2
            },
            itemStyle: {
              color: '#667eea'
            },
            data: userCounts
          }
        ]
      }
      
      userGrowthChart.setOption(option)
    }
  } catch (error) {
    console.error('加载用户增长趋势失败：', error)
  }
}

// 初始化学习活跃度图表
const initStudyActivityChart = async () => {
  if (!studyActivityChartRef.value) return
  
  studyActivityChart = echarts.init(studyActivityChartRef.value)
  
  try {
    const response = await getStudyActivityTrend(7)
    if (response.code === 200) {
      const chartData = response.data
      const days = chartData.map(item => {
        const date = new Date(item.date)
        const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()]
        return `${date.getMonth() + 1}/${date.getDate()}\n${weekDay}`
      })
      const studyCounts = chartData.map(item => item.count)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: days,
          axisLabel: {
            interval: 0,
            fontSize: 11
          }
        },
        yAxis: {
          type: 'value',
          name: '学习次数'
        },
        series: [
          {
            name: '学习次数',
            type: 'bar',
            barWidth: '60%',
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#84fab0' },
                { offset: 1, color: '#8fd3f4' }
              ]),
              borderRadius: [4, 4, 0, 0]
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#8fd3f4' },
                  { offset: 1, color: '#84fab0' }
                ])
              }
            },
            data: studyCounts
          }
        ]
      }
      
      studyActivityChart.setOption(option)
    }
  } catch (error) {
    console.error('加载学习活跃度趋势失败：', error)
  }
}

// 处理窗口大小变化
const handleResize = () => {
  if (userGrowthChart) {
    userGrowthChart.resize()
  }
  if (studyActivityChart) {
    studyActivityChart.resize()
  }
}
</script>

<style scoped>
.dashboard {
  padding: 24px;
}

.dashboard-header {
  margin-bottom: 24px;
}

.dashboard-header h2 {
  font-size: 24px;
  color: #303133;
  margin: 0 0 8px 0;
}

.subtitle {
  color: #909399;
  margin: 0;
}

.stat-cards {
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-icon {
  width: 64px;
  height: 64px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
}

.stat-card-primary .stat-icon {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-card-success .stat-icon {
  background: linear-gradient(135deg, #84fab0 0%, #8fd3f4 100%);
  color: white;
}

.stat-card-warning .stat-icon {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  color: white;
}

.stat-card-danger .stat-icon {
  background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
  color: white;
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.charts-section {
  margin-bottom: 24px;
}

.chart-card {
  background: white;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-card h3 {
  font-size: 18px;
  color: #303133;
  margin: 0 0 16px 0;
}

.chart-container {
  width: 100%;
  height: 300px;
}
</style>

